<?php
declare (strict_types = 1);

namespace app\adminapi\middleware;

use app\adminapi\extend\tools\jwt\Token;
use think\Exception;
use think\facade\Cache;
use think\facade\Response;
use think\exception\HttpException;

class Login extends Base
{
    /**
     * 阀值
     * @var int
     */
    protected $times = 3;

    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     */
    public function handle($request, \Closure $next)
    {
        try {
            # 判断token是否存在、并且保证token是有效的才能访问
            #  获取token
            $token = Token::getRequestToken();
            if (!$token) {
                return  fail('','请先登录');
            }
            # 验证token
            $user_id = Token::getUserId($token);
            if (!$user_id) {
                return  fail('','token失效');
            }
            # 权限检测
            # controller()获取当前访问的控制器名a
            # action()获取当前访问的方法名
            $current = strtolower($request->controller()).'/'.strtolower($request->action());
            $authList = cache('auth_list');# 获取缓存中的权限列表

            if (!in_array($current,$authList) && $user_id != 1) {
                return  fail('','无权限访问');
            }
            # token 认证成功、并且有权限访问
            # 接口频率限制
//            $this->throttleRequest();

            return $next($request);

        }catch (RuntimeException $exception){
            return  fail('','token 无效');
        }catch (Exception $exception) {
            return  fail('',$exception->getMessage());
        }catch (HttpException $exception) {
            return  fail('',$exception->getMessage());
        }


    }

    /**
     * 频率限制
     */
    protected function throttleRequest(){
        # 接口频率访问限制
        $ip = request()->ip();
        $ip = md5($ip.request()->pathinfo());
        # 获取缓存是否存在
        $isCache = cache($ip);
        if ($isCache) {
            if ($isCache > $this->times) {
                abort(2001,'访问此说过多，请稍后重试');
            }
            Cache::inc($ip);
        } else {

            cache($ip,1,180);
        }

        return true;
    }
}
